package com.minelx.hellopandas.core;

import com.alibaba.fastjson.JSONObject;

import java.util.Map;
import java.util.Objects;

import static java.util.Collections.emptyMap;
import static java.util.stream.Collectors.toMap;

public final class DataFrameDescription {

	private final String uri;

	private final Map<String, String> dtypes;

	private DataFrameDescription(String uri, Map<String, String> dtypes) {
		this.uri = uri;
		this.dtypes = dtypes;
	}

	public JSONObject dumpToJSON() {
		JSONObject result = new JSONObject();
		result.put("path", uri);
		result.put("dtypes", dtypes);
		return result;
	}

	public String uri() {
		return uri;
	}

	public Map<String, String> dtypes() {
		return dtypes;
	}

	@Override
	public boolean equals(Object o) {
		if (this == o) return true;
		if (o == null || getClass() != o.getClass()) return false;
		DataFrameDescription that = (DataFrameDescription) o;
		return uri.equals(that.uri) && dtypes.equals(that.dtypes);
	}

	@Override
	public int hashCode() {
		return Objects.hash(uri, dtypes);
	}

	@Override
	public String toString() {
		return "DataFrameDescription{" +
				"uri=" + uri +
				", dtypes=" + dtypes +
				'}';
	}

	public static DataFrameDescription create(String uri, Map<String, String> dtypes) {
		return new DataFrameDescription(uri, dtypes);
	}

	public static DataFrameDescription create(String uri) {
		return create(uri, emptyMap());
	}

	public static DataFrameDescription from(JSONObject data) {
		Map<String, String> dtypes = toStringMap(data.getJSONObject("dtypes"));
		// FIXME wait for: 'path' to 'uri'
		return create(data.getString("path"), dtypes);
	}

	private static Map<String, String> toStringMap(JSONObject jsonObject) {
		return jsonObject.entrySet()
				.stream().collect(toMap(Map.Entry::getKey, entry -> String.valueOf(entry.getValue())));
	}
}
